package demo.java8;

import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Created by zhangyanfei on 2018/3/30.
 * Function  apply    andThen  compose
 *
 * @author zhangyanfei
 * @date 2018/03/30
 */
public class FunctionDemo {

    public static void andThenTest(int i, Function<Integer, Integer> before, Function<Integer, Integer> after) {
        //andThen
        System.out.println(before.andThen(after).apply(i));
    }

    public static void composeTest(int i, Function<Integer, Integer> before, Function<Integer, Integer> after) {
        System.out.println(before.compose(after).apply(i));
    }

    public static void main(String[] args) {
        /**
         * Function
         */
        andThenTest(5, i -> i * 2, i -> i + 2);
        composeTest(5, i -> i * 2, i -> i + 2);
        /**
         * BiFunction
         */
        andThen(5, 5, (a, b) -> a * b, c -> c * 2);
        /**
         * Predicate
         */
        test(5, a -> a > 4);
        /**
         * consumer
         */
        int a = 10;
        consumerTest(a, b -> b = b * 2);
        System.out.println(a);

        /**
         * supplier 创建  接收一个构造函数
         */
        String str = supplierTest(String::new);
        System.out.println(str);
    }

    /**
     * BiFunction  2个入参
     *
     * andThen 一个方法只有一个返回参数
     */
    public static void andThen(int a, int b, BiFunction<Integer, Integer, Integer> before,
                               Function<Integer, Integer> after) {
        System.out.println(before.andThen(after).apply(a, b));
    }

    /**
     * Predicate 判断
     */
    public static void test(int a, Predicate<Integer> predicate) {
        System.out.println(predicate.test(a));
    }

    /**
     * Consumer 方法副作用
     */
    public static void consumerTest(int a, Consumer<Integer> consumer) {
        consumer.accept(a);
    }

    /**
     * supplier
     */
    public static String supplierTest(Supplier<String> supplier) {
        return supplier.get();
    }
}
